package com.finalBlog.Plugin;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.finalBlog.annotation.Action;
import com.finalBlog.common.SysConfig;
import com.finalBlog.util.FileSearchTool;
import com.jfinal.config.Routes;
import com.jfinal.plugin.IPlugin;

/**
 * finalBlog
 * 
 * 类/接口信息描述:通过解析controller 上的路径注解信息， 绑定到jfinal的 Routes上
 *
 * @author dengxc
 *
 */
@SuppressWarnings({"rawtypes","unchecked"})
public class RoutePlugin implements IPlugin{
	private static final Logger log = Logger.getLogger(RoutePlugin.class);
	
	private Routes routes;
	
	public RoutePlugin(Routes me){
		this.routes = me;
	}

	public boolean start() {
		String baseView = SysConfig.prop.get("base.viewpath");
		String conpackage = SysConfig.prop.get("con.package");
		List<Class> datas = new FileSearchTool().find(conpackage);
		for(Class ctrl : datas){
			Action annoctrl = (Action) ctrl.getAnnotation(Action.class);
			if(annoctrl==null){
				log.warn("类："+ctrl.getName()+"没有绑定访问路径到注解上！");
				continue;
			}else{
				String ctrlkey = annoctrl.url();
				if(StringUtils.isEmpty(ctrlkey)){
					log.error("类："+ctrl.getName()+"路由绑定失败，路径不能为空！");
				}else{
					if(ctrlkey.indexOf(",")!=-1){
						String []keys = ctrlkey.split(",");
						for(String key :keys){
							routes.add(key,ctrl,baseView);
						}
					}else{
						routes.add(ctrlkey,ctrl,baseView);
					}
				}
			}
		}
		return false;
	}

	public boolean stop() {
		return false;
	}


}
